package com.yk.faceapplication.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.allinpay.xed.R;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.yk.faceapplication.MyApplication;
import com.yk.faceapplication.adapter.AccountAdapter;
import com.yk.faceapplication.adapter.MyPagerAdapter;
import com.yk.faceapplication.callback.RequestCallback;
import com.yk.faceapplication.callback.UpdateBillStatusCallback;
import com.yk.faceapplication.entity.AccountItem;
import com.yk.faceapplication.entity.Advance;
import com.yk.faceapplication.entity.BankInfo;
import com.yk.faceapplication.entity.Bill;
import com.yk.faceapplication.entity.Member;
import com.yk.faceapplication.entity.Purpose;
import com.yk.faceapplication.entity.RecordRecent;
import com.yk.faceapplication.entity.StudyInfo;
import com.yk.faceapplication.http.RequestUrl;
import com.yk.faceapplication.util.ActivityUtil;
import com.yk.faceapplication.util.ImageUtil;
import com.yk.faceapplication.util.LogDebugger;
import com.yk.faceapplication.util.RequestUtil;
import com.yk.faceapplication.util.ViewFactory;
import com.yk.faceapplication.view.AutoVerticalScrollTextView;
import com.yk.faceapplication.view.CycleViewPager;
import com.yk.faceapplication.view.NoScrollViewPager;
import com.yk.faceapplication.view.PagerScrollView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HomeActivity extends BaseActivity {
    private NoScrollViewPager mPager;// 页卡内容
    private RadioGroup radioGroup;// 底部操作按钮

    private List<View> listViews; // Tab页面列表
    private View mView;// 我的
    private View billsView;//帐单
    private View loanView;// 借款

    private final int REQUEST_LOGIN = 1000;
    private final int REQUEST_BILLLIST = 1001;
    private final int REQUEST_SETTING = 1002;
    private final int REQUEST_AUTH = 1003;
    private final int REQUEST_FACE = 1004;

    private boolean getBank, getBankType, getWork, getStudy;


    // 帐单
    private Button addAccountBtn = null;
    private ImageView addAccountIV = null;
    private ListView accountListView = null;
    private LinearLayout emityLayout = null;
    private List<AccountItem> cccountItemList = new ArrayList<>();
    private TextView moneyTV = null;
    private TextView noteTV = null;
    private List<Bill> bills;
    private AccountAdapter accountAdapter;

    private PagerScrollView pagerScrollView;
    private int currentPage = 1;
    private boolean hasMore = true;

    //    private AccountAdapter accountAdapter = null;
    // 帐单

    // 我的
    private Button registerBtn;
    private TextView memberNameTV = null;
    private TextView memberMobileTV = null;
    private RelativeLayout mTopLayout = null;

    private RelativeLayout mLoginLayout = null;
    private RelativeLayout contactLayout = null;
    private RelativeLayout settingLayout = null;
    private RelativeLayout cardManageLayout = null;
    private RelativeLayout requestLayout = null;


    private TextView memberInfoTV = null;
    private TextView updatePwdTV = null;
    // 我的

    //借款
    private CycleViewPager advanceCycleView;
    private List<RecordRecent> records;
    private AutoVerticalScrollTextView horizontalScrollTV;
    private int recordPosition = 0;// 当前展示记录位置

    private List<Advance> advanceList1;
    private List<Advance> advanceList2;
    private List<Advance> advanceList3;
    private List<Advance> advanceList4;

    private ImageView advance2IV, advance3IV, advance4IV;
    private List<String> productShowIds = new ArrayList<>();

    private Button marketBtn;

    private String fileToken;
    private String xedFileGateUrl;


    //借款
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        loadingDialog = ActivityUtil.createLoadingDialog(this, "数据加载中,请稍候~");
        setTitle("帐单");
        LogDebugger.info("width:" + ActivityUtil.getScreenWidth(this));
        LogDebugger.info("height:" + ActivityUtil.getScreenHeight(this));
        LogDebugger.info("density:" + ActivityUtil.getScreenDensity(this));
        listViews = new ArrayList<View>();
        LayoutInflater mInflater = getLayoutInflater();
        mView = mInflater.inflate(R.layout.view_me, null);
        billsView = mInflater.inflate(R.layout.view_account, null);
        loanView = mInflater.inflate(R.layout.view_loan, null);
        listViews.add(billsView);
        listViews.add(loanView);
        listViews.add(mView);
        mPager = (NoScrollViewPager) findViewById(R.id.m_viewpager);
        mPager.setAdapter(new MyPagerAdapter(listViews));
        radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                checkLogin();
                switch (checkedId) {
                    case R.id.bills_btn:
                        mPager.setCurrentItem(0);
                        setTitle("帐单");
                        break;
                    case R.id.loan_btn:
                        getAdvance();
                        mPager.setCurrentItem(1);
                        setTitle("借款");
                        break;
                    case R.id.me_btn:
                        mPager.setCurrentItem(2);
                        setTitle("我的");
                        break;
                }
            }
        });
        //        getAdvance();
        getRecordsRecent();
        //        testSendMsg();
        //        sendMsg();
        //        getSwitch();
        //        getKey();

        marketBtn = (Button) loanView.findViewById(R.id.market_btn);
        marketBtn.setOnClickListener(this);
        initMeView();
        initBillsView();

        radioGroup.check(R.id.loan_btn);

    }

    private void checkLogin() {
        if (mApplication.getMember() == null) {
            if (!"".equals(preferences.getString("phone", ""))) {
                mTopLayout.setVisibility(View.VISIBLE);
                final Response.Listener<JSONObject> sListener = new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        LogDebugger.info("success:" + jsonObject.toString());
                        try {
                            if ("000000".equals(jsonObject.getString("code"))) {
                                Member member = JSON.parseObject(jsonObject.getString("data"), Member.class);
                                if(member == null){
                                    return;
                                }
                                mToken = jsonObject.getString("token");
                                editor.putString("token",mToken).commit();
                                mApplication.setToken(jsonObject.getString("token"));
                                mApplication.setMemberId(jsonObject.getString("tokenMemberId"));

                                mApplication.setMember(member);
                                memberNameTV.setText(mApplication.getMember().getRealName());
                                memberMobileTV.setText(mApplication.getMember().getMobile());
                                //                            if (member.getSubs().size() == 0) {
                                //                                Intent intent = new Intent(HomeActivity.this, AuthorizeActivity.class);
                                //                                startActivity(intent);
                                //                            }
                                getBills();
                                //                            getMonthBills();
                                initConfigData();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                final Response.ErrorListener eListener = new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        moneyTV.setText("0.00");
                        noteTV.setText("0笔");
                        volleyError.printStackTrace();
                        LogDebugger.info("fail:" + volleyError.getMessage());
                    }
                };

                LogDebugger.info(RequestUrl.LOGIN + "name=" + preferences.getString("phone", "") + "&password=" + preferences.getString("pwd", ""));

                try {
                    JSONObject jObj = new JSONObject();
                    JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, RequestUrl.LOGIN + "name=" + preferences.getString("phone", "") + "&password=" + preferences.getString("pwd", ""), jObj, sListener, eListener) {
                        @Override
                        protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                            JSONObject jsonObject;
                            try {
                                jsonObject = new JSONObject(new String(response.data, "UTF-8"));
                                return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                                return Response.error(new ParseError(e));
                            } catch (JSONException e) {
                                e.printStackTrace();
                                return Response.error(new ParseError(e));
                            }
                        }
                    };
                    ((MyApplication) this.getApplicationContext()).getrQueue().add(req);
                } catch (Exception e) {

                }
            } else {
                //            Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
                //            startActivity(intent);
                moneyTV.setText("0.00");
                noteTV.setText("0笔");
                mLoginLayout.setVisibility(View.VISIBLE);
            }
        }

    }

    @Override
    protected void onDestroy() {
        mApplication.setMember(null);
        super.onDestroy();
    }

    private List<ImageView> views = new ArrayList<ImageView>();
    private final int SHOW_NEXT_RECORD = 10001;// 展示下条记录
    private final int SHOW_RECORD_TIME = 5000;// 记录展示时间

    private void initLoanView() {
        horizontalScrollTV = (AutoVerticalScrollTextView) loanView.findViewById(R.id.textview_auto_roll);
        horizontalScrollTV.setText("恭喜" + records.get(recordPosition).getMobileShow() + "获得" + records.get(recordPosition).getLoanAmt() + "的额度");
        TextView textView = (TextView) horizontalScrollTV.getCurrentView();
        textView.setTextSize(14);
        textView.setSingleLine(true);
        textView.setGravity(Gravity.CENTER_VERTICAL);
        textView.setTextColor(getResources().getColor(R.color.textBlack));
        sendMessageDelayed(SHOW_NEXT_RECORD, SHOW_RECORD_TIME);
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case SHOW_NEXT_RECORD:
                if (recordPosition == records.size() - 1) {
                    recordPosition = 0;
                } else {
                    recordPosition++;
                }
                initLoanView();
                break;
        }
    }

    private void initMeView() {
        registerBtn = (Button) mView.findViewById(R.id.register_btn);
        registerBtn.setOnClickListener(this);
        memberNameTV = (TextView) mView.findViewById(R.id.member_name_tv);
        memberMobileTV = (TextView) mView.findViewById(R.id.member_mobile_tv);

        mTopLayout = (RelativeLayout) mView.findViewById(R.id.m_authorized_layout);
        mTopLayout.setOnClickListener(this);
        memberInfoTV = (TextView) mView.findViewById(R.id.contact_tv);
        memberInfoTV.setOnClickListener(this);
        updatePwdTV = (TextView) mView.findViewById(R.id.update_pwd_tv);
        updatePwdTV.setOnClickListener(this);

        mLoginLayout = (RelativeLayout) mView.findViewById(R.id.m_layout);

        settingLayout = (RelativeLayout) mView.findViewById(R.id.setting_layout);
        settingLayout.setOnClickListener(this);

        requestLayout = (RelativeLayout) mView.findViewById(R.id.request_layout);
        requestLayout.setOnClickListener(this);


        contactLayout = (RelativeLayout) mView.findViewById(R.id.contact_layout);
        contactLayout.setOnClickListener(this);

        cardManageLayout = (RelativeLayout) mView.findViewById(R.id.card_layout);
        cardManageLayout.setOnClickListener(this);

    }

    private int index = 0;

    private void initBillsView() {
        addAccountBtn = (Button) billsView.findViewById(R.id.add_btn);
        addAccountBtn.setOnClickListener(this);
        moneyTV = (TextView) billsView.findViewById(R.id.money_tv);
        noteTV = (TextView) billsView.findViewById(R.id.note_tv);
        accountListView = (ListView) billsView.findViewById(R.id.account_lv);
        pagerScrollView = (PagerScrollView) billsView.findViewById(R.id.action_scrollview);
        // 滑动到底部时加载更多活动
        pagerScrollView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        break;
                    case MotionEvent.ACTION_MOVE:
                        index++;
                        break;
                    default:
                        break;
                }

                if (event.getAction() == MotionEvent.ACTION_UP && index > 0) {
                    index = 0;
                    View view = ((ScrollView) v).getChildAt(0);
                    if (view.getMeasuredHeight() <= v.getScrollY() + v.getHeight()) {
                        // 加载数据代码
                        LogDebugger.info("bottom");
                        if (hasMore) {
                            currentPage++;
                            getBills();
                        }
                    }
                }

                return false;
            }

        });
    }

    private Dialog loadingDialog;

    private void initConfigData() {
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
        getBanks();
        getStudys();
        getBankTypes();
        getWorks();
    }


    private void initMemberInfo() {
        mApplication.setHomePageGetMember(false);
        mToken = mApplication.getToken();
        if (mToken == null) {
            mLoginLayout.setVisibility(View.VISIBLE);
            mTopLayout.setVisibility(View.GONE);
            moneyTV.setText("0.00");
            noteTV.setText("0笔");
            accountListView.setAdapter(null);
            mToken = null;
            mApplication.setMember(null);
            return;
        }
        if(mApplication.getMember() == null){
            return;
        }
        currentPage = 1;
        getBills();
        //        getMonthBills();
        initConfigData();

        memberNameTV.setText(mApplication.getMember().getRealName());
        memberMobileTV.setText(mApplication.getMember().getMobile());
        mTopLayout.setVisibility(View.VISIBLE);
        mLoginLayout.setVisibility(View.GONE);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_LOGIN) {
            if (resultCode == RESULT_OK) {
                //                initMemberInfo();
            }
        } else if (requestCode == REQUEST_BILLLIST) {
            if (resultCode == RESULT_OK) {
                if(mApplication.getMember() == null){
                    return;
                }
                currentPage = 1;
                getBills();
                //                getMonthBills();
            }
        } else if (requestCode == REQUEST_SETTING) {
            if (resultCode == RESULT_OK) {
                mLoginLayout.setVisibility(View.VISIBLE);
                mTopLayout.setVisibility(View.GONE);
                moneyTV.setText("0.00");
                noteTV.setText("0笔");
                accountListView.setAdapter(null);
                mToken = null;
                mApplication.setMember(null);
                mApplication.setToken(null);
            }
        } else if (requestCode == REQUEST_AUTH || requestCode == REQUEST_FACE) {
            if (resultCode == RESULT_OK) {
                getMember();
            }
        }

    }

    private void getMember() {
        Map<String, String> form = new HashMap<String, String>();

        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                try {
                    Member member = JSON.parseObject(jsonObject.getString("data"), Member.class);
                    mApplication.setMember(member);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        RequestUtil.request(this, RequestUrl.GET_MEMBER + "token=" + mToken, callback, form);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

            case R.id.setting_layout:
                //                if (mApplication.getMember() == null) {
                //                    Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
                //                    startActivityForResult(intent, REQUEST_LOGIN);
                //                    return;
                //                }
                //                if(!ActivityUtil.isAuth(this)){
                //                    Intent intent = new Intent(HomeActivity.this, AuthorizeActivity.class);
                //                    startActivityForResult(intent, REQUEST_AUTH);
                //                    return;
                //                }
                //                if(!ActivityUtil.isFace(this)){
                //                    Intent intent = new Intent(HomeActivity.this, MemberInfoActivity.class);
                //                    startActivityForResult(intent, REQUEST_FACE);
                //                    return;
                //                }
                Intent intent = new Intent(this, SettingActivity.class);
                startActivityForResult(intent, REQUEST_SETTING);
                break;
            case R.id.request_layout:
                if (mApplication.getMember() == null) {
                    intent = new Intent(HomeActivity.this, LoginActivity.class);
                    startActivityForResult(intent, REQUEST_LOGIN);
                    return;
                }
                if (!ActivityUtil.isAuth(this)) {
                    intent = new Intent(HomeActivity.this, AuthorizeActivity.class);
                    startActivityForResult(intent, REQUEST_AUTH);
                    return;
                }
                if (!ActivityUtil.isFace(this)) {
                    intent = new Intent(HomeActivity.this, MemberInfoActivity.class);
                    startActivityForResult(intent, REQUEST_FACE);
                    return;
                }
                intent = new Intent(this, RequestListActivity.class);
                startActivityForResult(intent, REQUEST_SETTING);
                break;
            case R.id.contact_layout:
                intent = new Intent(this, ContactActivity.class);
                startActivityForResult(intent, REQUEST_SETTING);
                break;
            case R.id.card_layout:
                if (mApplication.getMember() == null) {
                    intent = new Intent(HomeActivity.this, LoginActivity.class);
                    startActivityForResult(intent, REQUEST_LOGIN);
                    return;
                }
                if (!ActivityUtil.isAuth(this)) {
                    intent = new Intent(HomeActivity.this, AuthorizeActivity.class);
                    startActivityForResult(intent, REQUEST_AUTH);
                    return;
                }
                if (!ActivityUtil.isFace(this)) {
                    intent = new Intent(HomeActivity.this, MemberInfoActivity.class);
                    startActivityForResult(intent, REQUEST_FACE);
                    return;
                }
                intent = new Intent(this, CardListActivity.class);
                startActivity(intent);
                break;
            case R.id.market_btn:
                //                if (mToken == null) {
                //                    intent = new Intent(HomeActivity.this, LoginActivity.class);
                //                    startActivityForResult(intent, REQUEST_LOGIN);
                //                    return;
                //                }

                //                if (mApplication.getMember().getSubs() == null || mApplication.getMember().getSubs().isEmpty()) {
                //                    intent = new Intent(HomeActivity.this, AuthorizeActivity.class);
                //                    startActivityForResult(intent, REQUEST_AUTH);
                //                    return;
                //                }
                //                if (mApplication.getMember().getPeople() == null || mApplication.getMember().getCards() == null || mApplication.getMember().getCards().isEmpty()) {
                //                    intent = new Intent(HomeActivity.this, MemberInfoActivity.class);
                //                    startActivityForResult(intent, REQUEST_AUTH);
                //                    return;
                //                }

//                intent = new Intent(this, MarketActivity.class);
//                startActivity(intent);
                intent = new Intent(this, MarketListActivity.class);

                startActivity(intent);

                break;
            case R.id.register_btn:
                intent = new Intent(this, LoginActivity.class);
                //                startActivity(intent);
                startActivityForResult(intent, REQUEST_LOGIN);
                break;
            case R.id.add_btn:
                if (mApplication.getMember() == null) {
                    intent = new Intent(HomeActivity.this, LoginActivity.class);
                    startActivityForResult(intent, REQUEST_LOGIN);
                    return;
                }
                if (!ActivityUtil.isAuth(this)) {
                    intent = new Intent(HomeActivity.this, AuthorizeActivity.class);
                    startActivityForResult(intent, REQUEST_AUTH);
                    return;
                }
                if (!ActivityUtil.isFace(this)) {
                    intent = new Intent(HomeActivity.this, MemberInfoActivity.class);
                    startActivityForResult(intent, REQUEST_FACE);
                    return;
                }

                intent = new Intent(this, BillListActivity.class);
                startActivityForResult(intent, REQUEST_BILLLIST);
                break;
            case R.id.contact_tv:
                if (mApplication.getMember() == null) {
                    intent = new Intent(HomeActivity.this, LoginActivity.class);
                    startActivityForResult(intent, REQUEST_LOGIN);
                    return;
                }
                if (!ActivityUtil.isAuth(this)) {
                    intent = new Intent(HomeActivity.this, AuthorizeActivity.class);
                    startActivityForResult(intent, REQUEST_AUTH);
                    return;
                }
                intent = new Intent(this, MemberInfoActivity.class);
                startActivityForResult(intent, REQUEST_FACE);
                break;
            case R.id.update_pwd_tv:
                if (mApplication.getMember() == null) {
                    intent = new Intent(HomeActivity.this, LoginActivity.class);
                    startActivityForResult(intent, REQUEST_LOGIN);
                    return;
                }
                intent = new Intent(this, UpdatePwdActivity.class);
                startActivity(intent);
                break;
            case R.id.advance_2_img:
                clickAdvance(advanceList2.get(0));
                break;
            case R.id.advance_3_img:
                clickAdvance(advanceList3.get(0));
                break;
            case R.id.advance_4_img:
                clickAdvance(advanceList4.get(0));
                break;

        }
    }

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(Advance info, int position, View imageView) {
            if (advanceCycleView.isCycle()) {
                //				position = position - 1;
                //				 Toast.makeText(HomeActivity.this,
                //				 "position-->" + info.getContent(), Toast.LENGTH_SHORT)
                //				 .show();
                //                Intent intent = new Intent(HomeActivity.this, ProductActivity.class);
                //                System.out.println(info.getUrl());
                //                intent.putExtra("url", info.getContent());
                //                startActivity(intent);

                clickAdvance(info);
            }

        }

    };

    private void getAdvance() {


        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                try {
                    advanceList1 = JSON.parseArray(jsonObject.getJSONObject("data").getJSONObject("map").getString("1"), Advance.class);
                    advanceList2 = JSON.parseArray(jsonObject.getJSONObject("data").getJSONObject("map").getString("2"), Advance.class);
                    advanceList3 = JSON.parseArray(jsonObject.getJSONObject("data").getJSONObject("map").getString("3"), Advance.class);
                    advanceList4 = JSON.parseArray(jsonObject.getJSONObject("data").getJSONObject("map").getString("4"), Advance.class);
                    productShowIds.clear();
                    views.clear();
                    for (Advance advance : advanceList1) {
                        if (advance.getAdvUrl() != null && advance.getAdvUrl().startsWith("product")) {
                            productShowIds.add(advance.getAdvUrl().split("-")[1]);
                        }
                    }
                    for (Advance advance : advanceList2) {
                        if (advance.getAdvUrl() != null && advance.getAdvUrl().startsWith("product")) {
                            productShowIds.add(advance.getAdvUrl().split("-")[1]);
                        }
                    }
                    for (Advance advance : advanceList3) {
                        if (advance.getAdvUrl() != null && advance.getAdvUrl().startsWith("product")) {
                            productShowIds.add(advance.getAdvUrl().split("-")[1]);
                        }
                    }
                    for (Advance advance : advanceList4) {
                        if (advance.getAdvUrl() != null && advance.getAdvUrl().startsWith("product")) {
                            productShowIds.add(advance.getAdvUrl().split("-")[1]);
                        }
                    }
                    fileToken = jsonObject.getJSONObject("data").getString("fileToken");
                    xedFileGateUrl = jsonObject.getJSONObject("data").getString("xedFileGateUrl");
                    advanceCycleView = (CycleViewPager) getFragmentManager().findFragmentById(R.id.advance_cycle_view);
                    advance2IV = (ImageView) loanView.findViewById(R.id.advance_2_img);
                    advance3IV = (ImageView) loanView.findViewById(R.id.advance_3_img);
                    advance4IV = (ImageView) loanView.findViewById(R.id.advance_4_img);
                    ImageUtil.displayImage(HomeActivity.this, advanceList2.get(0).getAdvImageId(), advance2IV, fileToken,xedFileGateUrl);
                    ImageUtil.displayImage(HomeActivity.this, advanceList3.get(0).getAdvImageId(), advance3IV, fileToken,xedFileGateUrl);
                    ImageUtil.displayImage(HomeActivity.this, advanceList4.get(0).getAdvImageId(), advance4IV, fileToken,xedFileGateUrl);

                    advance2IV.setOnClickListener(HomeActivity.this);
                    advance3IV.setOnClickListener(HomeActivity.this);
                    advance4IV.setOnClickListener(HomeActivity.this);

                    // 将最后一个ImageView添加进来
                    views.add(ViewFactory.getImageView(HomeActivity.this, xedFileGateUrl+"?token=" + fileToken + "&fileId=" + advanceList1.get(advanceList1.size() - 1).getAdvImageId()));
                    for (int i = 0; i < advanceList1.size(); i++) {
                        views.add(ViewFactory.getImageView(HomeActivity.this, xedFileGateUrl+"?token=" + fileToken + "&fileId=" + advanceList1.get(i).getAdvImageId()));
                    }
                    // 将第一个ImageView添加进来
                    views.add(ViewFactory.getImageView(HomeActivity.this, xedFileGateUrl+"?token=" + fileToken + "&fileId=" + advanceList1.get(0).getAdvImageId()));

                    if (advanceCycleView == null)
                        return;
                    // 设置循环，在调用setData方法前调用
                    advanceCycleView.setCycle(true);

                    // 在加载数据前设置是否循环
                    advanceCycleView.setData(views, advanceList1, mAdCycleViewListener);
                    // 设置轮播
                    advanceCycleView.setWheel(true);

                    // 设置轮播时间，默认5000ms
                    advanceCycleView.setTime(5000);
                    // 设置圆点指示图标组居中显示，默认靠右
                    advanceCycleView.setIndicatorCenter();

                    showAdvancePoint();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        String urlToken = preferences.getString("token","").equals("")?"":
        "&token="+preferences.getString("token","")+"&appType=app";
        RequestUtil.getRequest(this, RequestUrl.GET_ADVANCE+urlToken, callback);
    }


    private void clickAdvance(Advance advance) {
        if(advance.getAdvUrl() == null || advance.getAdvUrl().isEmpty()){
            return;
        }
        if (advance.getAdvUrl().startsWith("product")) {
            if (mApplication.getMember() == null) {
                Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
                startActivityForResult(intent, REQUEST_LOGIN);
                return;
            }
            if (!ActivityUtil.isAuth(this)) {
                Intent intent = new Intent(HomeActivity.this, AuthorizeActivity.class);
                startActivityForResult(intent, REQUEST_AUTH);
                return;
            }
            if (!ActivityUtil.isFace(this)) {
                Intent intent = new Intent(HomeActivity.this, MemberInfoActivity.class);
                startActivityForResult(intent, REQUEST_FACE);
                return;
            }

            //跳转到产品详情
            String str[] = advance.getAdvUrl().split("-");
            clickAdvancePoint(str[1]);
            Intent intent = new Intent(HomeActivity.this, ProductDetailActivity.class);
            intent.putExtra("loanShowId", str[1]);
            startActivity(intent);
        } else {
            if (mApplication.getMember() == null) {
                Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
                startActivityForResult(intent, REQUEST_LOGIN);
                return;
            }
            if (!ActivityUtil.isAuth(this)) {
                Intent intent = new Intent(HomeActivity.this, AuthorizeActivity.class);
                startActivityForResult(intent, REQUEST_AUTH);
                return;
            }
            if (!ActivityUtil.isFace(this)) {
                Intent intent = new Intent(HomeActivity.this, MemberInfoActivity.class);
                startActivityForResult(intent, REQUEST_FACE);
                return;
            }
            //跳转到链接
            Intent intent = new Intent(HomeActivity.this, WebviewActivity.class);
            intent.putExtra("url", advance.getAdvUrl());
            startActivity(intent);
        }
    }

    private void showAdvancePoint() {
        if(productShowIds.isEmpty()){
            return;
        }
        Map<String, Object> form = new HashMap<String, Object>();
        form.put("productShowIds", productShowIds);
        form.put("showType", "1");
        form.put("userAgentType", "2");

        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {

            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        RequestUtil.request(this, RequestUrl.DOMAN+"allinpay.stat.all/statall/products/add", callback, form);
    }

    private void clickAdvancePoint(String loanshowid) {
        List<String> productShowIds = new ArrayList<String>();
        productShowIds.add(loanshowid);
        Map<String, Object> form = new HashMap<String, Object>();
        form.put("productShowIds", productShowIds);
        form.put("showType", "2");
        form.put("userAgentType", "2");

        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {

            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        RequestUtil.request(this, RequestUrl.DOMAN+"allinpay.stat.all/statall/products/add", callback, form);
    }

    private void getRecordsRecent() {

        Map<String, String> form = new HashMap<String, String>();

        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                try {
                    records = JSON.parseArray(jsonObject.getJSONObject("data").getString("records"), RecordRecent.class);
                    initLoanView();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        RequestUtil.request(this, RequestUrl.GET_RECORDS_RECENT, callback, form);
    }

    //    private void getMonthBills() {
    //
    //        Map<String, String> form = new HashMap<String, String>();
    //        form.put("memberId", mApplication.getMember().getId());
    //
    //        RequestCallback callback = new RequestCallback() {
    //            @Override
    //            public void success(JSONObject jsonObject) {
    //                try {
    //                    moneyTV.setText(jsonObject.getJSONObject("data").getString("total"));
    //                    noteTV.setText(jsonObject.getJSONObject("data").getString("count") + "笔");
    //                } catch (JSONException e) {
    //                    e.printStackTrace();
    //                }
    //            }
    //
    //            @Override
    //            public void fail(VolleyError volleyError) {
    //
    //            }
    //        };
    //        RequestUtil.request(this, RequestUrl.GET_BILLS_MONTH + "token=" + mToken, callback, form);
    //    }


    private void getBills() {
        hasMore = false;
        Map<String, String> form = new HashMap<String, String>();
        form.put("memberId", mApplication.getMember().getId());
        form.put("pageSize", "10");
        form.put("page", currentPage + "");

        final UpdateBillStatusCallback updateBillStatusCallback = new UpdateBillStatusCallback() {
            @Override
            public void updateStatus(Bill bill) {
                Intent intent = new Intent(HomeActivity.this, AccountSettingActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("account", bill);
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_BILLLIST);
            }
        };

        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                try {
                    if (currentPage == 1) {
                        if (bills != null) {
                            bills.clear();
                            bills.addAll(JSON.parseArray(jsonObject.getJSONObject("data").getString("data"), Bill.class));
                        } else {
                            bills = JSON.parseArray(jsonObject.getJSONObject("data").getString("data"), Bill.class);
                        }
                    } else {
                        bills.addAll(JSON.parseArray(jsonObject.getJSONObject("data").getString("data"), Bill.class));
                    }


                    if (JSON.parseArray(jsonObject.getJSONObject("data").getString("data"), Bill.class).size() > 9) {
                        hasMore = true;
                    } else {
                        hasMore = false;
                    }
                    moneyTV.setText(jsonObject.getJSONObject("data").getString("total"));
                    noteTV.setText(jsonObject.getJSONObject("data").getString("count") + "笔");
                    if (currentPage == 1) {
                        accountAdapter = new AccountAdapter(HomeActivity.this, bills, updateBillStatusCallback);
                        accountListView.setAdapter(accountAdapter);
                    } else {
                        accountAdapter.notifyDataSetChanged();
                    }

                    ViewGroup.LayoutParams params = accountListView.getLayoutParams();
                    params.height = (int) (ActivityUtil.dip2px(HomeActivity.this, (float) 175) * bills.size());
                    accountListView.setLayoutParams(params);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        RequestUtil.request(this, RequestUrl.GET_BILLS + "token=" + mToken, callback, form);
    }


    private void getBanks() {
        if (mApplication.getBanks() == null) {

            RequestCallback callback = new RequestCallback() {
                @Override
                public void success(JSONObject jsonObject) {
                    getBank = true;
                    checkLoadingDialogDismiss();
                    try {
                        mApplication.setBanks(JSON.parseArray(jsonObject.getString("data"), BankInfo.class));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void fail(VolleyError volleyError) {
                    getBank = true;
                    checkLoadingDialogDismiss();
                }
            };
            RequestUtil.getRequest(this, RequestUrl.GET_BANKS + "token=" + mToken, callback);
        } else {
            getBank = true;
            checkLoadingDialogDismiss();
        }

    }

    private void checkLoadingDialogDismiss() {
        if (getBank && getBankType && getWork && getStudy && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    private void getBankTypes() {
        if (mApplication.getBankTypes() == null) {

            RequestCallback callback = new RequestCallback() {
                @Override
                public void success(JSONObject jsonObject) {
                    getBankType = true;
                    checkLoadingDialogDismiss();
                    try {
                        mApplication.setBankTypes(JSON.parseArray(jsonObject.getString("data"), StudyInfo.class));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void fail(VolleyError volleyError) {
                    getBankType = true;
                    checkLoadingDialogDismiss();
                }
            };
            RequestUtil.getRequest(this, RequestUrl.GET_BANK_TYPES + "token=" + mToken, callback);
        } else {
            getBankType = true;
            checkLoadingDialogDismiss();
        }

    }

    private void getWorks() {
        if (mApplication.getWorks() == null) {
            RequestCallback callback = new RequestCallback() {
                @Override
                public void success(JSONObject jsonObject) {
                    getWork = true;
                    checkLoadingDialogDismiss();
                    try {
                        mApplication.setWorks(JSON.parseArray(jsonObject.getString("data"), Purpose.class));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void fail(VolleyError volleyError) {
                    getWork = true;
                    checkLoadingDialogDismiss();
                }
            };
            RequestUtil.getRequest(this, RequestUrl.GET_WORKS + "token=" + mToken, callback);
        } else {
            getWork = true;
            checkLoadingDialogDismiss();
        }
    }


    private void getStudys() {
        if (mApplication.getStudyInfos() == null) {
            RequestCallback callback = new RequestCallback() {
                @Override
                public void success(JSONObject jsonObject) {
                    getStudy = true;
                    checkLoadingDialogDismiss();
                    try {
                        mApplication.setStudyInfos(JSON.parseArray(jsonObject.getString("data"), StudyInfo.class));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void fail(VolleyError volleyError) {
                    getStudy = true;
                    checkLoadingDialogDismiss();
                }
            };
            RequestUtil.getRequest(this, RequestUrl.GET_STUDYS + "token=" + mToken, callback);
        } else {
            getStudy = true;
            checkLoadingDialogDismiss();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mApplication.isHomePageGetMember()) {
            initMemberInfo();
        }
    }
}
